package com.dooioo.pns.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.dooioo.pns.api.leancloud.LData;
import com.dooioo.pns.api.leancloud.LeanCloudRequestUtils;
import com.dooioo.pns.api.leancloud.Push;
import com.dooioo.pns.business.service.*;
import com.dooioo.pns.business.service.v2.BusinessSideUnDisturbService;
import com.dooioo.pns.entity.model.BusinessSide;
import com.dooioo.pns.entity.model.Message;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * PackageName:com.dooioo.pns.api.controller
 * Author: Jerry.hu
 * Create: Jerry.hu (2015-05-13 下午6:46)
 * Description:
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/api/message")
public class MessageController {
	@Autowired
	private MessageService messageService;
	@Autowired
	private AppInfoService appInfoService;
	@Autowired
	private DeviceInfoService deviceInfoService;
	@Autowired
	private BusinessSideService businessSideService;
	@Autowired
	private MessageReadService messageReadService;
	@Autowired
	private BusinessSideUnDisturbService businessSideUnDisturbService;
	@Autowired
	private LeanCloudRequestUtils leanCloudRequestUtils;
	/**
	 * 指定 工号发送 推送消息
	 * @param appId 应用appId
	 * @param businessId 推送方id
	 * @param prompt 标题
	 * @param recipients 接收方信息
	 * @param remark 备注信息
	 * @param touchdown 着陆页id
	 * @return
	 */
	@RequestMapping(value = "/user/push",method = RequestMethod.POST)
	@ResponseBody
	protected ResponseEntity<?> pushUser(
			@RequestParam(value = "appId",required = true)int appId,
			@RequestParam(value = "businessId",required = true)int businessId,
			@RequestParam(value = "prompt",required = true)String  prompt,
			@RequestParam(value = "recipients",required = true)String recipients,
			@RequestParam(value = "remark",required = false)String remark,
			@RequestParam(value = "touchdown",required = false,defaultValue = "0")int touchdown,
	        @RequestParam(value = "category" ,required = false,defaultValue = "0")int category,
	        @RequestParam(value = "extensionInfo" ,required = false)String extensionInfo
			){
		Message message = new Message(appId,businessId,prompt);
		Map<String,String> error = new HashMap<>();
		if(StringUtils.isBlank(recipients)){
			error.put("error","接收方不可为空");
			return new ResponseEntity<Object>(error, HttpStatus.BAD_REQUEST);
		}
		if(message.getAppId() == 0){
			error.put("error","目标appId 不可为空");
			return new ResponseEntity<Object>(error, HttpStatus.BAD_REQUEST);
		}
		if(StringUtils.isBlank(message.getPrompt())){
			error.put("error","消息标题不可为空");
			return new ResponseEntity<Object>(error, HttpStatus.BAD_REQUEST);
		}
		if(recipients.split(",").length > 100){
			error.put("error","接收方不可以超过100");
			return new ResponseEntity<Object>(error, HttpStatus.BAD_REQUEST);
		}
		if(!appInfoService.isExists(message.getAppId())){
			error.put("error","appId 未注册");
			return new ResponseEntity<Object>(error, HttpStatus.BAD_REQUEST);
		}
		BusinessSide businessSide = businessSideService.getBean(message.getBusinessId());
		if(businessSide == null){
			error.put("error","推送方未注册");
			return new ResponseEntity<Object>(error, HttpStatus.BAD_REQUEST);
		}
		List<String> userCodes = deviceInfoService.getRecipientsByUser(appId, recipients);
		if(userCodes.size() == 0){
			error.put("error","接收方未注册");
			return new ResponseEntity<Object>(error, HttpStatus.BAD_REQUEST);
		}
		message.setRecipients(userCodes.toString());
		message.setRemark(remark);
		message.setTouchdown(touchdown);
		message.setExtensionInfo(extensionInfo);
		message.setCategory(category);
		return sendPush(message,businessSide,userCodes);
	}

	private ResponseEntity<?> sendPush(Message message,BusinessSide businessSide, List<String> userCodes){
		List<String> originalUserCodes = new ArrayList<>();
		originalUserCodes.addAll(userCodes);
		List<String> unDisturbUserCodes = businessSideUnDisturbService.getUnDisturb(message.getBusinessId(), userCodes);
		userCodes.removeAll(unDisturbUserCodes);
		Map<String,String> error = new HashMap<>();
		try {
			if (messageService.insertMessage(message) > 0) {
				if(businessSide.isShow()){ //消息类型
					messageReadService.insertReadByUserCodes(message.getId(), message.getAppId(), originalUserCodes);
				}
				if(userCodes.size() >0) {
					Push push = getPush(message,true,businessSide);
					push.setChannels(userCodes.toArray(new String[userCodes.size()]));
//					new Thread(new LeancloudPushMessage(message.getId(), push, appInfoService.getHeaderMap(message.getAppId()), messageService)).start();
					leanCloudRequestUtils.send(message.getId(),push,appInfoService.getHeaderMap(message.getAppId()));
				}
				if(unDisturbUserCodes.size() >0){
					Push push = getPush(message,false,businessSide);
					push.setChannels(unDisturbUserCodes.toArray(new String[unDisturbUserCodes.size()]));
//					new Thread(new LeancloudPushMessage(message.getId(), push, appInfoService.getHeaderMap(message.getAppId()), messageService)).start();
					leanCloudRequestUtils.send(message.getId(),push,appInfoService.getHeaderMap(message.getAppId()));
				}
				return ResponseEntity.ok(null);
			}else{
				error.put("error","发送失败");
				return new ResponseEntity<Object>(error, HttpStatus.BAD_REQUEST);
			}
		}catch (Exception e){
			error.put("error",e.toString());
			return new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	/**
	 * 指定app 发送推送消息
	 * @param appId appId
	 * @param businessId 推送方id
	 * @param prompt 标题
	 * @param remark 备注信息
	 * @param touchdown 着陆页 地址
	 * @return ResponseEntity
	 */
	@RequestMapping(value = "/app/push",method = RequestMethod.POST)
	@ResponseBody
	protected ResponseEntity<?> pushApp(
			@RequestParam(value = "appId",required = true)int appId,
			@RequestParam(value = "businessId",required = true)int businessId,
			@RequestParam(value = "prompt",required = true)String  prompt,
			@RequestParam(value = "remark",required = false)String remark,
			@RequestParam(value = "touchdown",required = false,defaultValue = "0")int touchdown,
			@RequestParam(value = "category" ,required = false,defaultValue = "0")int category,
			@RequestParam(value = "extensionInfo" ,required = false)String extensionInfo
			){
		Message message = new Message(appId,businessId,prompt);
		Map<String,String> error = new HashMap<>();
		if(message.getAppId() == 0){
			error.put("error","目标appId 不可为空");
			return new ResponseEntity<Object>(error, HttpStatus.BAD_REQUEST);
		}
		if(StringUtils.isBlank(message.getPrompt())){
			error.put("error","消息标题不可为空");
			return new ResponseEntity<Object>(error, HttpStatus.BAD_REQUEST);
		}
		if(!appInfoService.isExists(message.getAppId())){
			error.put("error","appId 未注册");
			return new ResponseEntity<Object>(error, HttpStatus.BAD_REQUEST);
		}
		BusinessSide businessSide = businessSideService.getBean(message.getBusinessId());
		if(businessSide == null){
			error.put("error","推送方未注册");
			return new ResponseEntity<Object>(error, HttpStatus.BAD_REQUEST);
		}
		List<String> userCodes = deviceInfoService.getRecipientsByAppId(appId);
		message.setRecipients("a" + message.getAppId());
		message.setRemark(remark);
		message.setTouchdown(touchdown);
		message.setExtensionInfo(extensionInfo);
		message.setCategory(category);
		return sendPush(message,businessSide,userCodes);
	}


	/**
	 * 消息详情信息
	 * @param messageId 消息id
	 * @return 消息详情
	 */
	@RequestMapping(value = "/{userCode}/{messageId}",method = RequestMethod.GET)
	public ResponseEntity<?> view(@PathVariable int userCode,@PathVariable int messageId){
		Message message = messageService.getBean(messageId);
		Map<String,String> error = new HashMap<>();
		if(message == null){
			error.put("error","消息不存在");
			return new ResponseEntity<Object>(error, HttpStatus.NOT_FOUND);
		}
		messageReadService.updateStatus(userCode, message.getId(), Message.MESSAGE_STATUS_READ);
		return ResponseEntity.ok(message);
	}

	/**
	 * 消息列表
	 * @param userCode 用户工号
	 * @param appId app 应用Id
	 * @param businessId 业务推送方id
	 * @return list
	 */
	@RequestMapping(value = "/{userCode}/{appId}/{businessId}",method = RequestMethod.GET)
	public ResponseEntity<?> list(@PathVariable int userCode,@PathVariable int appId,@PathVariable int businessId,
								 @RequestParam(value = "pageSize",defaultValue = "20")int pageSize,
								 @RequestParam(value = "pageNo",defaultValue = "1")int pageNo){
		return ResponseEntity.ok(messageService.getMessagePagination(userCode,appId,businessId,pageSize,pageNo));
	}

	/**
	 * 更新消息已读
	 * @param userCode 工号
	 * @param messageIds
	 * @return
	 */
	@RequestMapping(value = "/{userCode}/read",method = RequestMethod.PUT)
	public ResponseEntity<?> read(@PathVariable int userCode,
	                              @RequestParam(value = "messageIds",required = true)String messageIds){
		JSONArray messageIdArray;
		Map<String,String> result = new HashMap<>();
		try {
			messageIdArray = JSON.parseArray(messageIds);
		}catch (Exception e){
			result.put("error","消息id JSONArray 格式不对");
			return new ResponseEntity<Object>(result, HttpStatus.BAD_REQUEST);
		}

		if(messageReadService.readMessage(userCode,messageIdArray)){
				result.put("message","更新成功");
				result.put("code","0");
		}else {
			result.put("code","0");
			result.put("message","设置已读失败");
		}
		return  ResponseEntity.ok(result);
	}

	/**
	 * 获取员工的消息的未读条数
	 * @param userCode
	 * @return
	 */
	@RequestMapping(value = "/{userCode}/unread",method = RequestMethod.GET)
	protected ResponseEntity<?> getUnread(@PathVariable int userCode){
		Map<String,Integer> map = new HashMap<>();
		map.put("count",messageReadService.getUnreadCount(userCode,1000));
		return ResponseEntity.ok(map);
	}

	/**
	 * 获取发送的实体
	 * @param message
	 * @return
	 */
	private Push getPush(Message message,boolean disturb,BusinessSide businessSide){
		Push push = new Push();
		LData lData = new LData();
		if(businessSide.isShow()){
			if(!StringUtils.isBlank(message.getRemark())){
				if(message.getRemark().length() > 30){
					lData.setAlert(businessSide.getName()+":"+message.getRemark().substring(0,30)+"...");
				}else{
					lData.setAlert(businessSide.getName()+":"+message.getRemark()+"...");
				}
			} else {
				lData.setAlert(message.getPrompt());
			}
		}else {
			lData.setAlert(message.getPrompt());
		}
		lData.setBusinessId(String.valueOf(message.getBusinessId()));
		lData.setExtensionInfo(message.getExtensionInfo());
		lData.setTouchdown(String.valueOf(message.getTouchdown()));
		lData.setCategory(String.valueOf(message.getCategory()));
		if(!disturb){
			lData.setSound("");
		}
		push.setData(lData);
		return push;
	}
}
